﻿using System.Linq;
using UnityEngine;
namespace Project
{
    public enum MonsterState
    {
        None,
        Attak,
        Move
    }
    public class BuildMonster_AI : MonsterBase
    {
        public MonsterState monsterState = MonsterState.None;
        public float AttackRange = 10f; // 射程距离
        public float interval;//攻击间隔
        private float time;//计时器
        private void Start()
        {
            monRigi2D = GetComponent<Rigidbody2D>();
            playerTrans = GameObject.FindGameObjectWithTag("Player").transform;
            monsterState = MonsterState.Move;
        }

        private void Update()
        {
            
            if (playerTrans == null) return;

            float dis = Vector3.Distance(transform.position, playerTrans.position);
            if (dis > AttackRange && monsterState == MonsterState.Move)
            {
                MoveTowardsPlayer();
            }
            else
            {
                monsterState = MonsterState.Attak;
                Attack();
            }
        }

        private void Attack()
        {
            monRigi2D.velocity = Vector3.zero;
            time += Time.deltaTime;
            if (time >= interval)
            {
                time -= interval;

                Vector2 position = transform.position;
                Vector2 direction = transform.right;

                // 发射圆形射线
                RaycastHit2D[] hits = Physics2D.CircleCastAll(position, AttackRange, direction);
                RaycastHit2D hit = hits.FirstOrDefault(e => e.collider.CompareTag("Player"));

                monsterState = MonsterState.Move;
                if (hit == false) return;

                Debug.Log("攻击到玩家");
            }
        }
        private void OnDrawGizmos()
        {
            Gizmos.DrawWireSphere(transform.position, AttackRange);
        }
    }
}

